package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.datasource.entities.MaterialExtend;
import com.jsh.erp.datasource.vo.MaterialExtendVo4List;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.materialExtend.MaterialExtendService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.GdsUtils;
import com.jsh.erp.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jijiaqing
 */
@RestController
@RequestMapping(value = "/materialsExtend")
@Api(tags = {"商品价格扩展"})
public class MaterialExtendController {
    private Logger logger = LoggerFactory.getLogger(MaterialExtendController.class);
    @Resource
    private MaterialExtendService materialExtendService;

    @GetMapping(value = "/getDetailList")
    @ApiOperation(value = "价格信息列表")
    public BaseResponseInfo getDetailList(@RequestParam("materialId") Long materialId,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<MaterialExtendVo4List> dataList = new ArrayList<MaterialExtendVo4List>();
            if (materialId != 0) {
                dataList = materialExtendService.getDetailList(materialId);
            }
            JSONObject outer = new JSONObject();
            outer.put("total", dataList.size());
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (MaterialExtendVo4List md : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", md.getId());
                    item.put("barCode", md.getBarCode());
                    item.put("commodityUnit", md.getCommodityUnit());
                    if (StringUtil.isNotEmpty(md.getSku())) {
                        item.put("sku", md.getSku());
                    }
                    item.put("purchaseDecimal", md.getPurchaseDecimal());
                    item.put("commodityDecimal", md.getCommodityDecimal());
                    item.put("wholesaleDecimal", md.getWholesaleDecimal());
                    item.put("lowDecimal", md.getLowDecimal());
                    dataArray.add(item);
                }
            }
            outer.put("rows", dataArray);
            res.code = 200;
            res.data = outer;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    /**
     * 根据条码查询商品信息
     *
     * @param barCode
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getInfoByBarCode")
    @ApiOperation(value = "根据条码查询商品信息")
    public BaseResponseInfo getInfoByBarCode(@RequestParam("barCode") String barCode,
                                             HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MaterialExtend materialExtend = materialExtendService.getInfoByBarCode(barCode);
            res.code = 200;
            res.data = materialExtend;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @Autowired
    MaterialService materialService;

    /**
     * 校验条码是否存在
     *
     * @param id
     * @param barCode
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/checkIsBarCodeExist")
    @ApiOperation(value = "校验条码是否存在")
    public BaseResponseInfo checkIsBarCodeExist(@RequestParam("id") Long id,
                                                @RequestParam("barCode") String barCode,
                                                HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<>();
        try {
            int exist = materialExtendService.checkIsBarCodeExist(id, barCode);
            if (exist > 0) {
                map.put("status", true);
            } else {
                map.put("status", false);
            }
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @Resource
    public RedisTemplate redisTemplate;

    private GdsUtils.Item getGdsItem(String barCode) {
        var obj = redisTemplate.opsForValue().get("gds:" + barCode);
        if (null != obj) {
            return GdsUtils.get( obj.toString());
        }
        String str = GdsUtils.getGds(barCode);
        if (null != str && str.contains(barCode)) {
            redisTemplate.opsForValue().set("gds:" + barCode, str);
        }
        GdsUtils.check();
        return GdsUtils.get(str);
    }

    @GetMapping(value = "/importGds")
    @ApiOperation(value = "导入商品二维码信息")
    public BaseResponseInfo importGds(@RequestParam("barCode") String barCode
            , HttpServletRequest request) {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<>();
        try {
            MaterialExtend materialExtend = materialExtendService.getInfoByBarCode(barCode);
            if (null != materialExtend && materialExtend.getId() != null) {
                logger.warn("商品已经存在系统barCode={}", barCode);
                return res;
            }

            var item = getGdsItem(barCode);
            if (null == item) {
                logger.warn("未找到商品信息={}", barCode);
                return res;
            }

            String str = "{\"name\":\"怡宝矿泉水\",\"unit\":\"个\",\"unitId\":\"\"," +
                    "\"meList\":[{\"id\":\"16687854354130632367\",\"barCode\":\"" + barCode + "\",\"commodityUnit\":\"个\",\"sku\":\"\",\"purchaseDecimal\":\"0\",\"commodityDecimal\":\"0\",\"wholesaleDecimal\":\"0\",\"lowDecimal\":\"0\"}],\"stock\":[{\"id\":\"14\",\"name\":\"仓库1\",\"initStock\":\"0\",\"lowSafeStock\":\"\",\"highSafeStock\":\"\"},{\"id\":\"15\",\"name\":\"仓库2\",\"initStock\":\"0\",\"lowSafeStock\":\"\",\"highSafeStock\":\"\"},{\"id\":\"17\",\"name\":\"仓库3\",\"initStock\":\"0\",\"lowSafeStock\":\"\",\"highSafeStock\":\"\"}],\"sortList\":[],\"imgName\":\"\",\"meDeleteIdList\":[]}";
            var obj = JSONObject.parseObject(str);
            obj.put("name", item.getDescription());
            obj.put("model", item.getBrandcn());
            materialService.insertMaterial(obj, request);
            res.code = 200;
            res.data = map;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }
}
